﻿using UnityEngine;
using System.Collections;

namespace Util
{
    public class ObjUtil : Object
    {

        /// <summary>
        /// 创建精灵    
        /// </summary>
        /// <param name="atlas">贴图</param>
        /// <param name="rect">贴图坐标</param>
        /// <param name="pixPerUnit"></param>
        /// <param name="pivot"></param>
        /// <param name="pos"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public static GameObject createSprite(Texture2D atlas, Rect rect, float pixPerUnit, Vector2 pivot, Vector2 pos, string name)
        {
            GameObject gameObj = createObject(pos, name);
            SpriteRenderer spriteRenderder = gameObj.AddComponent<SpriteRenderer>();
            Sprite sprite = Sprite.Create(atlas, rect, pivot, pixPerUnit);
            spriteRenderder.sprite = sprite;

            return gameObj;
        }

        /// <summary>
        /// 修改精灵    
        /// </summary>
        /// <param name="atlas">贴图</param>
        /// <param name="rect">贴图坐标</param>
        /// <param name="pixPerUnit"></param>
        /// <param name="pivot"></param>
        /// <param name="pos"></param>
        /// <param name="sourceObj">精灵所在对象</param>
        /// <returns></returns>
        public static void changeSprite(GameObject sourceObj,Texture2D atlas, Rect rect, float pixPerUnit, Vector2 pivot)
        {
            SpriteRenderer spriteRenderder = sourceObj.GetComponent<SpriteRenderer>();
            Sprite sprite = Sprite.Create(atlas, rect, pivot, pixPerUnit);
            spriteRenderder.sprite = sprite;

            //return gameObj;
        }

        /// <summary>
        /// 从预设创建物体
        /// </summary>
        /// <param name="path"></param>
        /// <param name="pos"></param>
        /// <returns></returns>
        public static GameObject createPrefab(string path, Vector2 pos)
        {
            GameObject prefab = Resources.Load(path) as GameObject;
            GameObject obj = Instantiate(prefab, new Vector3(pos.x, pos.y, 0f), Quaternion.identity) as GameObject;
            return obj;
        }

        /// <summary>
        /// 创建空物体
        /// </summary>
        /// <param name="pos">位置</param>
        /// <param name="name">名字</param>
        /// <returns></returns>
        public static GameObject createObject(Vector2 pos, string name)
        {
            GameObject obj = new GameObject(name);
            obj.transform.position = new Vector3(pos.x, pos.y, 0f);
            return obj;
        }
    }
}
